﻿using System;
using iTeamyou.LTS.Core.Models;
using Microsoft.EntityFrameworkCore;

namespace iTeamyou.LTS.Core.Services
{
	public class SyncService
	{
        public MainDBContext _dbContext;
        public SyncService()
		{
            _dbContext = new MainDBContext();
        }

        public SyncSupplier Save(SyncSupplier syncSupplier)
        {
            syncSupplier.SyncId = Guid.NewGuid().ToString("N");
            _dbContext.SyncSuppliers.Add(syncSupplier);
            _dbContext.SaveChanges();
            return syncSupplier;
        }

        public SyncProduct Save(SyncProduct syncProduct)
        {
            syncProduct.SyncId = Guid.NewGuid().ToString("N");
            _dbContext.SyncProducts.Add(syncProduct);
            _dbContext.SaveChanges();
            return syncProduct;
        }

        public SyncBarcode Save(SyncBarcode syncBarcode)
        {
            syncBarcode.SyncId = Guid.NewGuid().ToString("N");
            _dbContext.SyncBarcodes.Add(syncBarcode);
            _dbContext.SaveChanges();
            return syncBarcode;
        }

        public SyncBatch Save(SyncBatch syncBatch)
        {
            syncBatch.SyncId = Guid.NewGuid().ToString("N");
            _dbContext.SyncBatches.Add(syncBatch);
            _dbContext.SaveChanges();
            return syncBatch;
        }

        public void Update(SyncSupplier syncSupplier)
        {
            var exist = _dbContext.SyncSuppliers.Find(syncSupplier.SyncId);
            if (exist != null)
            {
                syncSupplier.IsSynced = true;
                _dbContext.Entry(exist).CurrentValues.SetValues(syncSupplier);
                _dbContext.SaveChanges();
            }
        }
        //新增批量修改供应商
        public void BatchUpdate(List<SyncSupplier> syncSuppliers)
        {
            Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 开始批量更新，共 {syncSuppliers.Count} 条供应商数据。");
            if (syncSuppliers == null || !syncSuppliers.Any()) return;

            // 提取所有待更新的SyncId
            var syncIds = syncSuppliers.Select(s => s.SyncId).ToList();

            // 查询所有存在的实体
            var existingEntities = _dbContext.SyncSuppliers.Where(s => syncIds.Contains(s.SyncId)).ToList();

            // 转换为字典，便于快速匹配
            var existDict = existingEntities.ToDictionary(s => s.SyncId);

            foreach (var syncSupplier in syncSuppliers)
            {
                if (existDict.TryGetValue(syncSupplier.SyncId, out var exist))
                {
                    // 更新实体的值
                    _dbContext.Entry(exist).CurrentValues.SetValues(syncSupplier);
                    // 标记为已同步
                    exist.IsSynced = true;
                }
            }
            // 批量保存
            _dbContext.SaveChanges();
        }
        public void Update(SyncProduct syncProduct)
        {
            var exist = _dbContext.SyncProducts.Find(syncProduct.SyncId);
            if (exist != null)
            {
                syncProduct.IsSynced = true;
                _dbContext.Entry(exist).CurrentValues.SetValues(syncProduct);
                _dbContext.SaveChanges();
            }
        }
        //新增批量修改商品
        public void BatchUpdate(List<SyncProduct> syncProducts)
        {
            Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] 开始批量插入，共 {syncProducts.Count} 条产品数据。");
            if (syncProducts == null || !syncProducts.Any()) return;

            var syncIds = syncProducts.Select(p => p.SyncId).ToList();

            // 获取所有要更新的实体
            var existingEntities = _dbContext.SyncProducts.Where(p => syncIds.Contains(p.SyncId)).ToList();

            var existDict = existingEntities.ToDictionary(p => p.SyncId);

            foreach (var item in syncProducts)
            {
                if (existDict.TryGetValue(item.SyncId, out var entity))
                {
                    // 更新实体的值
                    _dbContext.Entry(entity).CurrentValues.SetValues(item);
                    // 标记为已同步
                    entity.IsSynced = true;
                }
            }
            // 一次性保存所有更改
            _dbContext.SaveChanges();
        }
        public void Update(SyncBarcode syncBarcode)
        {
            var exist = _dbContext.SyncBarcodes.Find(syncBarcode.SyncId);
            if (exist != null)
            {
                syncBarcode.IsSynced = true;
                _dbContext.Entry(exist).CurrentValues.SetValues(syncBarcode);
                _dbContext.SaveChanges();
            }
        }
        public void Update(SyncBatch syncBatch)
        {
            var exist = _dbContext.SyncBatches.Find(syncBatch.SyncId);
            if (exist != null)
            {
                syncBatch.IsSynced = true;
                _dbContext.Entry(exist).CurrentValues.SetValues(syncBatch);
                _dbContext.SaveChanges();
            }
        }
        //新增批量修改商品
        public void BatchUpdate(List<SyncBatch> syncBatches)
        {
            Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 开始批量更新，共 {syncBatches.Count} 条入库管理数据。");
            if (syncBatches == null || !syncBatches.Any()) return;

            var syncIds = syncBatches.Select(sb => sb.SyncId).ToList();

            // 批量查询存在的 SyncBatch 记录
            var existingBatches = _dbContext.SyncBatches.Where(sb => syncIds.Contains(sb.SyncId)).ToList();

            // 创建一个字典以便快速查找
            var existingBatchesDict = existingBatches.ToDictionary(sb => sb.SyncId, sb => sb);

            // 准备一个列表来跟踪需要更新的实体
            var entriesToUpdate = new List<SyncBatch>();

            foreach (var syncBatch in syncBatches)
            {
                if (existingBatchesDict.TryGetValue(syncBatch.SyncId, out var existingBatch))
                {
                    existingBatch.IsSynced = true;
                    // 仅更新需要更改的属性
                    _dbContext.Entry(existingBatch).CurrentValues.SetValues(syncBatch);

                    // 将更新后的实体添加到列表中
                    entriesToUpdate.Add(existingBatch);
                }
            }

            // 保存所有更改
            _dbContext.SaveChanges();
        }

        public List<SyncSupplier> GetSyncSuppliers()
        {
            return _dbContext.SyncSuppliers.Where(f => f.IsSynced == false).ToList();
        }

        public List<SyncProduct> GetSyncProducts()
        {
            return _dbContext.SyncProducts.Where(f => f.IsSynced == false).ToList();
        }

        public List<SyncBarcode> GetSyncBarcodes()
        {
            return _dbContext.SyncBarcodes.Where(f => f.IsSynced == false).ToList();
        }

        public List<SyncBatch> GetSyncBatches()
        {
            return _dbContext.SyncBatches.Where(f => f.IsSynced == false).ToList();
        }

        //public void Save(SyncSupplier syncSupplier)
        //{
        //    var sqlString = "INSERT INTO `syncsuppliers` (`Id`, `RefId`, `SId`, `Name`, `Contact`, `ContactNumber`, `Region`, `SyncTime`, `SyncFrom`, `IsSynced`) VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10)";
        //    _dbContext.Database.ExecuteSqlRaw(sqlString, syncSupplier.Id, syncSupplier.RefId, syncSupplier.SId, syncSupplier.Name, syncSupplier.Contact, syncSupplier.ContactNumber, syncSupplier.Region, syncSupplier.SyncTime, syncSupplier.SyncFrom, syncSupplier.IsSynced);
        //}

        //public void Save(SyncProduct syncProduct)
        //{
        //    var sqlString = "INSERT INTO `syncproducts` (`Id`, `PId`, `Name`, `SupplierRefId`, `OriginPlace`, `Specification`, `SectionId`, `SyncTime`, `SyncFrom`, `IsSynced`) VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10)";
        //    _dbContext.Database.ExecuteSqlRaw(sqlString, syncProduct.Id, syncProduct.PId, syncProduct.Name, syncProduct.SupplierRefId, syncProduct.OriginPlace, syncProduct.Specification, syncProduct.SectionId, syncProduct.SyncTime, syncProduct.SyncFrom, syncProduct.IsSynced);
        //}

        //public void Save(SyncBarcode syncBarcode)
        //{
        //    //_dbContext.SyncBarcodes.Add(syncBarcode);
        //    var sqlString = "INSERT INTO `SyncBarcodes` (`PId`, `UPC`, `SyncTime`, `SyncFrom`, `IsSynced`) VALUES (@p1, @p2, @p3, @p4, @p5)";
        //    _dbContext.Database.ExecuteSqlRaw(sqlString, syncBarcode.PId, syncBarcode.UPC, syncBarcode.SyncTime, syncBarcode.SyncFrom, syncBarcode.IsSynced);
        //}

        //public void Save(SyncBatch syncBatch)
        //{
        //    var sqlString = "INSERT INTO `syncbatches` (`Id`, `BId`, `Number`, `Quantity`, `ProductName`, `SupplierName`, `ProductSKU`, `OrderNumber`, `EntryDatetime`, `WarehouseNumber`, `DateDue`, `ProducedDate`, `SyncTime`, `SyncFrom`, `IsSynced`) VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15)";
        //    _dbContext.Database.ExecuteSqlRaw(sqlString, syncBatch.Id, syncBatch.BId, syncBatch.Number, syncBatch.Quantity, syncBatch.ProductName, syncBatch.SupplierName, syncBatch.ProductSKU, syncBatch.OrderNumber, syncBatch.EntryDatetime, syncBatch.WarehouseNumber, syncBatch.DateDue, syncBatch.ProducedDate, syncBatch.SyncTime, syncBatch.SyncFrom, syncBatch.IsSynced);
        //}
    }
}

